package com.xiaoxiang.cameracontrol.zsocket;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class FrameMessage {
	private byte[] complete_message = null;
	private byte[] remains = new byte[0];
	private int frame_head_length=4;
	
	public FrameMessage(byte[] data) {
		this.complete_message = new byte[0];
		this.remains = data;
		if(data.length>this.frame_head_length) {
			this.calculate(data);
		}
	}
	
	private void calculate(byte[] data) {
		int expect_length = FrameMessage.bytes_to_int(FrameMessage.sub_list(data, 0, this.frame_head_length), "big");
		data = FrameMessage.sub_list(data, this.frame_head_length, -1);
		if(data.length>expect_length) {
			this.complete_message = FrameMessage.sub_list(data, 0, expect_length);
			this.remains = FrameMessage.sub_list(data, expect_length, -1);
		}
		if(data.length==expect_length) {
			this.complete_message = data;
			this.remains = new byte[0];
		}
	}
	
	public byte[] get_complete_message() {
		return this.complete_message;
	}
	
	public byte[] get_remain_message() {
		return this.remains;
	}
	
	public static byte[] att_list(byte[] data1, byte[] data2) {
		byte[] result = new byte[data1.length+data2.length];
		for(int i=0;i<data1.length;i++) {
			result[i] = data1[i];
		}
		for(int i=data1.length;i<result.length;i++) {
			result[i] = data2[i-data1.length];
		}
		return result;
	}
	
	public static byte[] sub_list(byte[] data, int start, int end) {
		if(end<0) end = data.length;
		if(start<0) start=0;
		if(end-start==data.length) return data;
		byte[] result = new byte[end-start];
		for(int i=0;i<result.length;i++) {
			result[i]=data[start+i];
		}
		return result;
	}
	
	
	public static int bytes_to_int(byte[] data, String mode) {
		int result = 0;
		ByteOrder order = ByteOrder.BIG_ENDIAN;
		if(mode=="litter") order = ByteOrder.LITTLE_ENDIAN;
		result = ByteBuffer.wrap(data, 0, data.length).order(order).getInt();
		
		return result;
	}
	
	public static byte[] int_to_bytes(int data, String mode) {
		ByteOrder order = ByteOrder.BIG_ENDIAN;
		if(mode=="litter") order = ByteOrder.LITTLE_ENDIAN;
		byte[] result = ByteBuffer.allocate(4).order(order).putInt(data).array();
		return result;
	}
	
	private static byte[] reverse_list(byte[] data) {
		byte[] result= new byte[data.length];
		int len = data.length;
		int mid = data.length>>1;
		for(int i=0;i<=mid;i++) {
			result[i] = data[len-1-i];
			result[len-1-i] = data[i];
		}
		return result;
	}
	

}
